package com.lzx.dormsys.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.lzx.dormsys.bean.UserBean;
import com.lzx.dormsys.constant.Constants;
import com.lzx.dormsys.core.AjaxResult;
import com.lzx.dormsys.core.controller.BaseController;
import com.lzx.dormsys.core.page.TableDataInfo;
import com.lzx.dormsys.core.redis.RedisCache;
import com.lzx.dormsys.entity.LoginBody;
import com.lzx.dormsys.service.UserService;
import com.lzx.dormsys.util.jwt.JwtToken;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.security.sasl.AuthenticationException;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/userAction")
public class UserAction extends BaseController {
    @Autowired
    UserService userService;

    @Autowired
    private RedisCache redisCache;

    @RequestMapping("/login")
    @ResponseBody
    public AjaxResult login(UserBean userBean) {
        UserBean user = userService.login(userBean);
        if (user != null) {
            return AjaxResult.success("登录成功!");
        }
        return AjaxResult.error("用户名或密码错误！");
    }

    /**
     * 登录接口
     */
    @PostMapping("/loginVerify")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        UserBean userBean = new UserBean();
        userBean.setLoginname(loginBody.getLoginname());
        userBean.setPwd(loginBody.getPwd());
        UserBean user = userService.login(userBean);
        // 设置返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("userInfo", user);

        String verifyKey = Constants.CAPTCHA_CODE_KEY + loginBody.getUuid();
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);

        Gson gson = new Gson();
        String jsonUserInfo = gson.toJson(loginBody);

        // 调用jwt
        JwtToken jwtToken = new JwtToken();
        String jwtTokenSting = jwtToken.generateToken(jsonUserInfo);

        // 设置token返给前端
        result.put("token", jwtTokenSting);

        if (user == null) {
            return AjaxResult.error("用户名或密码错误！");
        } else if (captcha == null || !loginBody.getCode().equalsIgnoreCase(captcha)) {
            return AjaxResult.error("验证码错误！");
        }

        List<Map<String, Object>> loginUserMenus = userService.getLoginUserMenus(user.getUserid());
        result.put("routes", loginUserMenus);

        return AjaxResult.success(result);
    }

    @GetMapping("/profile")
    public AjaxResult profile(String userid) {
        UserBean userBean = userService.getProfileByUserid(userid);
        return AjaxResult.success(userBean);
    }

    @PutMapping("/profile")
    public AjaxResult updateProfile(@RequestBody UserBean userBean) {
        try {
            int update = userService.update(userBean);
        } catch (Exception e) {
            return AjaxResult.error("信息修改失败！");
        }
        return AjaxResult.success("信息更新成功！");
    }

    @PostMapping("/updatePwd")
    public AjaxResult updateUserPwd(@RequestBody Map<String, String> data, HttpServletRequest request) throws Exception {
        JwtToken jwtToken = new JwtToken();
        String loginUserInfo = jwtToken.getLoginUserInfo(request);
        System.out.println(loginUserInfo);
        Gson gson = new Gson();
        LoginBody user = gson.fromJson(loginUserInfo, LoginBody.class);

        String token;
        if (!user.getPwd().equals(data.get("oldPassword"))) {
            return AjaxResult.error("修改密码失败，旧密码错误");
        } else if (user.getPwd().equals(data.get("newPassword"))) {
            return AjaxResult.error("新密码不能与旧密码相同");
        } else {
            // 修改密码
            userService.setPassword(data.get("userid"), data.get("newPassword"));
            // 重新生成token
            user.setPwd(data.get("newPassword"));
            token = jwtToken.generateToken(gson.toJson(user));
        }
        return AjaxResult.success("修改成功", token);
    }

    @PostMapping("/resetPwd")
    public AjaxResult resetUserPwd(@RequestBody Map<String, String> data) throws Exception {
        try {
            userService.setPassword(data.get("userid"), data.get("newPassword"));
        } catch (Exception e) {
            return AjaxResult.error("密码重置失败");
        }
        return AjaxResult.success("密码重置成功");
    }

    @GetMapping("/list")
    public TableDataInfo list(UserBean userBean) {
        startPage();
        List<UserBean> userBeans = userService.queryData(userBean);
        return getDataTable(userBeans);
    }

    @PostMapping("/add")
    public AjaxResult add(@RequestBody UserBean userBean) {
        int insert = userService.insert(userBean);

        if (insert <= 0) {
            return AjaxResult.success("新增失败");
        }
        return AjaxResult.success("新增成功");
    }

    @DeleteMapping("/{userid}")
    public AjaxResult remove(@PathVariable String userid) {
        int i = userService.deleteByPrimaryKey(userid);
        System.out.println(i);
        if (i <= 0) {
            return AjaxResult.error("删除失败");
        }
        return AjaxResult.success("删除成功");
    }
}
